package org.u2ml.app.rest;

import java.util.ArrayList;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.u2ml.app.business.UserService;
import org.u2ml.app.domain.RESTResponse;
import org.u2ml.app.domain.User;
import org.u2ml.app.domain.Project;

@Component
@Path("/users")
public class UserResource {
	@Autowired
	private UserService userService;

	@POST
	@Produces(MediaType.TEXT_XML)
	public RESTResponse newUser(User user) {
		RESTResponse response = new RESTResponse();
		if (user.getOid() != null)
			throw new WebApplicationException(Status.BAD_REQUEST);
		if (user.getProjects() != null)
			throw new WebApplicationException(Status.BAD_REQUEST);
		if(user.getName() == null || user.getName().isEmpty() ||
				user.getPassword() == null || user.getPassword().isEmpty() ||
				user.getEmail() == null || user.getEmail().isEmpty()) {
			throw new WebApplicationException(Status.BAD_REQUEST);
		}
		user.setProjects(new ArrayList<Project>());
		user.setContributedProjects(new ArrayList<Project>());
		response.addData(userService.save(user));
		return response;
	}
	
	@GET
	@Produces(MediaType.TEXT_XML)
	public RESTResponse getAll() {
		RESTResponse response = new RESTResponse();
		response.addAllData(userService.get());
		return response;
	}
	

	@GET
	@Produces(MediaType.TEXT_XML)
	@Path("/user/{oid}")
	public RESTResponse find(@PathParam("oid") Long oid) {
		RESTResponse response = new RESTResponse();
		if (oid == null) {
			throw new WebApplicationException(Status.BAD_REQUEST);
		}
		User user = userService.find(oid);
		if (user == null)
			response.setErrorCode("user_not_found");
		response.addData(user);
		return response;
	}

	@PUT
	@Path("/user/{login}")
	public RESTResponse update(@PathParam("login") String name, User user) {
		RESTResponse response = new RESTResponse();
		if (user == null)
			throw new WebApplicationException(Status.BAD_REQUEST);
		User userFromDB = userService.findByName(name);
		if (userFromDB == null) {
			response.setErrorCode("user_not_found");
		} else {
			user.setOid(userFromDB.getOid());
			userService.update(user);
		}
		response.addData(user);
		return response;
	}

	@GET
	@Produces(MediaType.TEXT_XML)
	@Path("/user/search/{input}")
	public RESTResponse findByNameOrEmail(@PathParam("input") String input) {
		RESTResponse response = new RESTResponse();
		if (input == null) {
			throw new WebApplicationException(Status.BAD_REQUEST);
		}
		User user = userService.findByName(input);
		if(user == null)
			user = userService.findByEmail(input);
		
		if (user == null) {
			response.setWarningCode("user_not_found");
		} else {
			response.addData(user);
		}
		return response;
	}
}
